package com.atguigu.serurity.config;

import com.atguigu.serurity.filter.JwtAuthenticationTokenFilter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启权限注解配置的功能
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	/**
	 * @Bean只能在配置类中使用
	 * @return
	 */
    @Resource
	private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;



	//PasswordEncoder是一个密码解析器
	@Bean
	public PasswordEncoder passwordEncoder(){

		return new BCryptPasswordEncoder();
	}

	@Bean
	public AuthenticationManager authenticationManagerBean() throws Exception {
		return super.authenticationManagerBean();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
				//关闭csrf
				.csrf().disable()
				//不通过Session获取SecurityContext
				.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				.authorizeRequests()
				// 对于登录接口 允许匿名访问
				.antMatchers("/api/**",
						"/swagger-resources/**", "/webjars/**", "/v2/**", "/doc.html/**").anonymous()
				// 除上面外的所有请求全部需要鉴权认证
				.anyRequest().authenticated();
		/**
		 *在进行UsernamePasswordAuthenticationFilter校验之前先进行token的校验=>过滤器
		 */
		http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
/*		//添加授权，认证的异常处理器
		http.exceptionHandling()
				//添加认证异常处理
				.authenticationEntryPoint(authenticationExceptionHandler)
                //添加授权失败处理器
		        .accessDeniedHandler(accessDeniedHandler);*/

		//允许跨域->前后端的端口不一样=》
		//http.cors();
	}

}
